; (function ($) {

    jQuery.fn.sdxmenu = function (options) {
        var defaults = {
            trigger: ".sdx-trigger",
        };

        defaults = $.extend(defaults, options);
        //触发按钮
        var trigger = $(defaults.trigger);
        //包裹菜单sdxmenu-wrapper
        var $this = $(this);
        //控制是否开关
        var isOpen = false;
        var $subnav = null;

        trigger.on("mouseover", function () {
            $this.addClass("sdxmenu-open-part");
        });

        trigger.on("mouseout", function () {
            $this.removeClass("sdxmenu-open-part");
        });

        $this.on("mouseover", function () {
            openMenu();
        });

        trigger.on("click", function (ev) {
            if (isOpen) {
                closeMenu();
            } else {
                openMenu();
            }
        });

        //控制收缩
        // 侧边菜单伸缩
        $(".sdxmenu-item-has-submenu >a").on("click", function () {
            $navHasSubnav = jQuery(this).parent();
            $subnav = $navHasSubnav.find(".sdxmenu-submenu").first();
            $navHasSubnav.siblings().find(".sdxmenu-submenu").slideUp(180).parent().removeClass("open");
            $subnav.slideToggle(180, function () {
                $navHasSubnav.toggleClass("open");
            });
        });

        //打开菜单
        function openMenu() {
            if (isOpen) return;
            isOpen = true;
            //展开的时候关闭折叠
            $('.navbar-collapse').collapse('hide')
            //添加遮罩层
            $('<div class="sd-mask-modal"></div>').prependTo("body");

            //遮罩层一个点击事件点击关闭
            $(".sd-mask-modal").on("click", function () {
                $(this).remove();
                closeMenu();
            });
            $this.removeClass("sdxmenu-open-part");
            $this.addClass("sdxmenu-open-all");
        }

        //关闭菜单
        function closeMenu() {
            if (!isOpen) return;
            isOpen = false;
            //关闭后收缩菜单
            $subnav !==null ?  $subnav.slideUp(180) : '';
  
            $this.removeClass("sdxmenu-open-part");
            $this.removeClass("sdxmenu-open-all");
        }
    };

    
    // 在插件内部初始化

    $(function() {

        $("[data-sdxmenu]").sdxmenu();

    }) 

})(jQuery);
